/**
 * PitObstacle - 坑洞障碍物
 * 地面上的坑洞，玩家必须跳跃才能安全通过
 */

import { Obstacle, ObstacleType, ObstacleOptions } from '../Obstacle'
import type { Entity } from '../Entity'

/**
 * 坑洞类型枚举
 */
export enum PitVariant {
  SMALL = 'small',    // 小坑洞 - 容易跳过
  MEDIUM = 'medium',  // 中等坑洞 - 需要准确时机
  LARGE = 'large',    // 大坑洞 - 需要长跳
  SPIKE = 'spike'     // 尖刺坑洞 - 额外伤害
}

/**
 * 坑洞障碍物配置选项
 */
export interface PitObstacleOptions extends Omit<ObstacleOptions, 'obstacleType'> {
  variant?: PitVariant
  depth?: number
  hasSpikes?: boolean
}

/**
 * 坑洞障碍物类
 * @class
 * @example
 * const pit = new PitObstacle({
 *   x: 300,
 *   y: 350,
 *   width: 80,
 *   height: 50,
 *   variant: PitVariant.MEDIUM
 * });
 */
export class PitObstacle extends Obstacle {
  public readonly variant: PitVariant
  public readonly depth: number
  public readonly hasSpikes: boolean
  private animationTime: number = 0
  private particleEffects: Array<{x: number, y: number, life: number}> = []

  /**
   * 创建坑洞障碍物
   * @param options - 坑洞配置选项
   */
  constructor(options: PitObstacleOptions) {
    const variant = options.variant || PitVariant.MEDIUM
    const depth = options.depth || PitObstacle.getDefaultDepth(variant)
    const hasSpikes = options.hasSpikes || variant === PitVariant.SPIKE

    super({
      ...options,
      obstacleType: ObstacleType.PIT,
      damage: PitObstacle.getDamageByVariant(variant, hasSpikes),
      scoreValue: PitObstacle.getScoreByVariant(variant),
      canBeDestroyed: false // 坑洞不能被摧毁
    })

    this.variant = variant
    this.depth = depth
    this.hasSpikes = hasSpikes
  }

  /**
   * 根据变体获取默认深度
   * @param variant - 坑洞变体
   * @returns 默认深度
   */
  private static getDefaultDepth(variant: PitVariant): number {
    switch (variant) {
      case PitVariant.SMALL:
        return 20
      case PitVariant.MEDIUM:
        return 35
      case PitVariant.LARGE:
        return 50
      case PitVariant.SPIKE:
        return 40
      default:
        return 35
    }
  }

  /**
   * 根据变体获取伤害值
   * @param variant - 坑洞变体
   * @param hasSpikes - 是否有尖刺
   * @returns 伤害值
   */
  private static getDamageByVariant(variant: PitVariant, hasSpikes: boolean): number {
    let baseDamage = 1
    
    switch (variant) {
      case PitVariant.SMALL:
        baseDamage = 1
        break
      case PitVariant.MEDIUM:
        baseDamage = 2
        break
      case PitVariant.LARGE:
        baseDamage = 2
        break
      case PitVariant.SPIKE:
        baseDamage = 3
        break
    }
    
    return hasSpikes ? baseDamage + 1 : baseDamage
  }

  /**
   * 根据变体获取分数值
   * @param variant - 坑洞变体
   * @returns 分数值
   */
  private static getScoreByVariant(variant: PitVariant): number {
    switch (variant) {
      case PitVariant.SMALL:
        return 20
      case PitVariant.MEDIUM:
        return 30
      case PitVariant.LARGE:
        return 40
      case PitVariant.SPIKE:
        return 50
      default:
        return 30
    }
  }

  /**
   * 更新坑洞障碍物逻辑
   * @param deltaTime - 时间差
   */
  protected updateObstacle(deltaTime: number): void {
    this.animationTime += deltaTime

    // 更新粒子效果
    this.updateParticleEffects(deltaTime)

    // 生成新的粒子效果（尘土、碎石等）
    if (Math.random() < 0.1) {
      this.generateParticle()
    }

    // 尖刺坑洞的特殊效果
    if (this.hasSpikes) {
      this.updateSpikeEffects(deltaTime)
    }
  }

  /**
   * 更新粒子效果
   * @param deltaTime - 时间差
   */
  private updateParticleEffects(deltaTime: number): void {
    this.particleEffects = this.particleEffects.filter(particle => {
      particle.life -= deltaTime
      particle.y -= 0.5 // 粒子向上飘
      particle.x += (Math.random() - 0.5) * 0.2 // 轻微水平移动
      return particle.life > 0
    })
  }

  /**
   * 生成粒子
   */
  private generateParticle(): void {
    if (this.particleEffects.length < 10) {
      this.particleEffects.push({
        x: this.x + Math.random() * this.width,
        y: this.y + this.height - 5,
        life: 1000 + Math.random() * 2000 // 1-3秒生命周期
      })
    }
  }

  /**
   * 更新尖刺效果
   * @param _deltaTime - 时间差
   */
  private updateSpikeEffects(_deltaTime: number): void {
    // 尖刺可以有伸缩动画
    // 这里可以添加尖刺的动态行为
  }

  /**
   * 渲染坑洞障碍物
   * @param ctx - Canvas渲染上下文
   */
  render(ctx: CanvasRenderingContext2D): void {
    if (!this.visible) return

    if (this.sprite && this.sprite.image) {
      super.render(ctx)
    } else {
      this.renderDefault(ctx)
    }

    // 渲染粒子效果
    this.renderParticleEffects(ctx)
  }

  /**
   * 渲染默认外观
   * @param ctx - Canvas渲染上下文
   */
  protected renderDefault(ctx: CanvasRenderingContext2D): void {
    // 渲染坑洞主体
    this.renderPitBase(ctx)
    
    // 渲染深度效果
    this.renderDepthEffect(ctx)
    
    // 渲染尖刺（如果有）
    if (this.hasSpikes) {
      this.renderSpikes(ctx)
    }
    
    // 渲染边缘效果
    this.renderEdgeEffects(ctx)
  }

  /**
   * 渲染坑洞基础
   * @param ctx - Canvas渲染上下文
   */
  private renderPitBase(ctx: CanvasRenderingContext2D): void {
    // 创建渐变效果模拟深度
    const gradient = ctx.createLinearGradient(this.x, this.y, this.x, this.y + this.height)
    gradient.addColorStop(0, '#1a1a1a') // 顶部较亮
    gradient.addColorStop(0.5, '#0d0d0d') // 中间较暗
    gradient.addColorStop(1, '#000000') // 底部最暗
    
    ctx.fillStyle = gradient
    ctx.fillRect(this.x, this.y, this.width, this.height)
  }

  /**
   * 渲染深度效果
   * @param ctx - Canvas渲染上下文
   */
  private renderDepthEffect(ctx: CanvasRenderingContext2D): void {
    // 添加阴影层来增强深度感
    const shadowLayers = 3
    for (let i = 0; i < shadowLayers; i++) {
      const alpha = 0.3 - (i * 0.1)
      const offset = i * 2
      
      ctx.fillStyle = `rgba(0, 0, 0, ${alpha})`
      ctx.fillRect(
        this.x + offset,
        this.y + offset,
        this.width - offset * 2,
        this.height - offset * 2
      )
    }
  }

  /**
   * 渲染尖刺
   * @param ctx - Canvas渲染上下文
   */
  private renderSpikes(ctx: CanvasRenderingContext2D): void {
    const spikeCount = Math.floor(this.width / 15)
    const spikeHeight = 8 + Math.sin(this.animationTime * 0.005) * 2 // 动态高度
    
    ctx.fillStyle = '#666666'
    
    for (let i = 0; i < spikeCount; i++) {
      const spikeX = this.x + (i * (this.width / spikeCount)) + 5
      const spikeY = this.y + this.height - spikeHeight
      
      // 绘制三角形尖刺
      ctx.beginPath()
      ctx.moveTo(spikeX, this.y + this.height)
      ctx.lineTo(spikeX + 5, spikeY)
      ctx.lineTo(spikeX + 10, this.y + this.height)
      ctx.closePath()
      ctx.fill()
      
      // 添加尖刺高光
      ctx.fillStyle = '#888888'
      ctx.beginPath()
      ctx.moveTo(spikeX + 1, this.y + this.height - 1)
      ctx.lineTo(spikeX + 5, spikeY + 1)
      ctx.lineTo(spikeX + 3, this.y + this.height - 1)
      ctx.closePath()
      ctx.fill()
      
      ctx.fillStyle = '#666666'
    }
  }

  /**
   * 渲染边缘效果
   * @param ctx - Canvas渲染上下文
   */
  private renderEdgeEffects(ctx: CanvasRenderingContext2D): void {
    // 渲染坑洞边缘的破碎效果
    ctx.strokeStyle = '#444444'
    ctx.lineWidth = 2
    
    // 左边缘
    ctx.beginPath()
    for (let y = this.y; y < this.y + this.height; y += 5) {
      const offset = Math.sin((y + this.animationTime * 0.001) * 0.1) * 2
      ctx.lineTo(this.x + offset, y)
    }
    ctx.stroke()
    
    // 右边缘
    ctx.beginPath()
    for (let y = this.y; y < this.y + this.height; y += 5) {
      const offset = Math.sin((y + this.animationTime * 0.001 + Math.PI) * 0.1) * 2
      ctx.lineTo(this.x + this.width + offset, y)
    }
    ctx.stroke()
  }

  /**
   * 渲染粒子效果
   * @param ctx - Canvas渲染上下文
   */
  private renderParticleEffects(ctx: CanvasRenderingContext2D): void {
    for (const particle of this.particleEffects) {
      const alpha = particle.life / 3000 // 根据生命周期调整透明度
      ctx.fillStyle = `rgba(139, 69, 19, ${alpha})` // 棕色尘土
      ctx.fillRect(particle.x, particle.y, 2, 2)
    }
  }

  /**
   * 处理碰撞逻辑
   * @param _player - 玩家实体
   * @returns 是否处理了碰撞
   */
  protected handleCollision(_player: Entity): boolean {
    // 坑洞碰撞会造成坠落伤害
    console.log(`玩家掉入${this.variant}坑洞，造成${this.damage}点坠落伤害`)
    
    // 生成碰撞粒子效果
    for (let i = 0; i < 5; i++) {
      this.generateParticle()
    }
    
    return true
  }

  /**
   * 获取跳跃所需的最小距离
   * @returns 最小跳跃距离
   */
  getRequiredJumpDistance(): number {
    switch (this.variant) {
      case PitVariant.SMALL:
        return this.width + 10
      case PitVariant.MEDIUM:
        return this.width + 20
      case PitVariant.LARGE:
        return this.width + 30
      case PitVariant.SPIKE:
        return this.width + 25
      default:
        return this.width + 20
    }
  }

  /**
   * 检查玩家是否可以安全跳过
   * @param playerJumpDistance - 玩家跳跃距离
   * @returns 是否可以安全跳过
   */
  canPlayerJumpOver(playerJumpDistance: number): boolean {
    return playerJumpDistance >= this.getRequiredJumpDistance()
  }

  /**
   * 获取障碍物描述
   * @returns 描述信息
   */
  getDescription(): string {
    const baseDesc = super.getDescription()
    const spikeInfo = this.hasSpikes ? '(带尖刺)' : ''
    const jumpDistance = this.getRequiredJumpDistance()
    return `${baseDesc} - ${this.variant}坑洞 ${spikeInfo} (需跳跃距离: ${jumpDistance})`
  }
}